import json
import requests
import argparse
import base64
'''
curl -k -H "Authorization: ApiKey Z0JjWEtITUI1M3FaRkxBUTUyLWo6c0pZdjNWTUxSYWFlYW9VZWMyWGZzQQ==" https://localhost:9200/_cluster/healt
https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api.html
'''
# 解析watcher index,写入


class ElasticRestore:
	
	elastic_url='https://localhost:9200'
	kibana_url='http://localhost:5601'
	es_apikey='cmUxVjlZNEJMS0F5NFVqREdTQng6d3VCbjlHMU9RZzZyRUJkNFpoYzFsUQ=='
	basic_auth='ZWxhc3RpYzp6M1VWT1JXVXdxNz01RkErNEhpbQ=='
	# headers = {'Authorization': 'ApiKey '+es_apikey,"Content-Type": "application/json; charset=UTF-8"}
	headers = {"kbn-xsrf":"true","Authorization":"Basic "+basic_auth,"Content-Type": "application/json; charset=UTF-8"}

	def restore_watcher(self,path):
		skip=[]
		total = 0
		with open(path,'r',encoding='utf-8') as f:
			s = f.read()
			# s = s.replace('172.16.16.11','online-cn-test.foodorder.vip')
			# s = s.replace('"scheme":"http"','"scheme":"https"')
			# s = s.replace('"port":8080','"port":443')
			# s = s.replace('"port":8400','"port":443')
			data = json.loads(s)

			watches = data['hits']['hits']
			for watcher in watches:
				print('id='+watcher['_id'])
				id = watcher['_id']
				body = watcher['_source']
				#跳过系统自带的
				if body['metadata']['name'].startswith('X-Pack'):
					skip.append(body['metadata']['name'])
					continue
				response = requests.put(self.elastic_url+'/_watcher/watch/'+id,json=body, headers=self.headers,verify= False)
				print('update watch res='+response.text)
				total+=1
				# 设置默认状态为关闭				
				response = requests.put(self.elastic_url+'/_watcher/watch/'+id+'/_deactivate',headers=self.headers,verify = False)
		return total
	def restore_role(self,path):
		total = 0
		with open(path,'r',encoding='utf-8') as f:
			data = json.loads(f.read())
			for item in data:
				# 跳过内置角色
				# print('metadata:'+item['metadata'])
				if item['metadata'].get('_reserved')==True:
					continue
				name = item['name']
				del item['name']
				del item['transient_metadata']
				del item['_transform_error']
				body = {
					'elasticsearch':item['elasticsearch'],
					'kibana':item['kibana']
				}
				response = requests.put(self.kibana_url+'/api/security/role/'+name,json=body, headers=self.headers,verify=False)
				print('update role res=',response)
				total+=1
		return total	
	def restore_user(self,path):
		with open(path,'r',encoding='utf-8') as f:
			data = json.loads(f.read())
			total = 0
			for username in data.keys():
				user = data[username]
				body = {
					"password":'newpassword',
					"roles":user["roles"],
					"full_name":user["full_name"],
					"email":user["email"],
					"enabled":user["enabled"]
				}
				response = requests.put(self.elastic_url+'/_security/user/'+username,json=body, headers=self.headers,verify= False)
				print(response.text)
				total+=1
		return total
if __name__=="__main__":
	parser = argparse.ArgumentParser(description='Elastic Config Backup')
	parser.add_argument('-es', '--elastic_url', default='http://localhost:9200',
                    help='elastic url,not ends with /',required=True)
	parser.add_argument('-kibana', '--kibana_url', default='http://localhost:9200',
                    help='kibana url,not ends with /',required=True)
	parser.add_argument('-u', '--username', default='elastic',
                    help='elastic auth username',required=True)
	parser.add_argument('-p', '--password',
                    help='elastic auth password',required=True)
	parser.add_argument('-t', '--type',default='',
                    help='type',required=True)
	parser.add_argument('-f', '--file',default='',
                    help='import json file path',required=True)

	args = parser.parse_args()

	restore = ElasticRestore()
	restore.elastic_url=args.elastic_url
	restore.kibana_url=args.kibana_url
	restore.basic_auth=str(base64.b64encode((args.username+':'+args.password).encode("utf-8")),'utf-8')
	restore.headers=headers = {"kbn-xsrf":"true","Authorization":"Basic "+restore.basic_auth,"Content-Type": "application/json; charset=UTF-8"}
	restore.path = args.file

	total = 0
	if args.type=='watcher':
		total = restore.restore_watcher(restore.path)
	elif args.type=='role':
		total =  restore.restore_role(restore.path)
	elif args.type=='user':
		total = restore.restore_user(restore.path)
	else:
		print('unknow type:'+args.type)
	print('total='+str(total))
	
	


